#include "gpio.h"
#include "lcd_tm1621c.h"

static uint8_t wr_pin_num;
static uint8_t data_pin_num;

#define LCD_WR_OUTPUT_INIT()    hal_gpio_pin_init((gpio_pin_e)wr_pin_num, GPIO_OUTPUT)
#define LCD_WR_OUTPUT_LOW()     hal_gpio_fast_write((gpio_pin_e)wr_pin_num, 0)
#define LCD_WR_OUTPUT_HIGH()    hal_gpio_fast_write((gpio_pin_e)wr_pin_num, 1)

#define LCD_DATA_OUTPUT_INIT()  hal_gpio_pin_init((gpio_pin_e)data_pin_num, GPIO_OUTPUT)
#define LCD_DATA_OUTPUT_LOW()   hal_gpio_fast_write((gpio_pin_e)data_pin_num, 0)
#define LCD_DATA_OUTPUT_HIGH()  hal_gpio_fast_write((gpio_pin_e)data_pin_num, 1)


/*static void delay(uint16_t dly_cnt)
{
	while(dly_cnt--);
}*/


void tm1621_tx_bits_msb(uint8_t dat, uint8_t bit_cnt)
{
    for(uint8_t i=0;i<bit_cnt;i++)
    {
        LCD_WR_OUTPUT_LOW();
        if(i < 8)
        {
            if(dat&0x80)
            {
                LCD_DATA_OUTPUT_HIGH();
            }
            else
            {
                LCD_DATA_OUTPUT_LOW();
            }
            dat<<=1;
        }
        else
        {
            LCD_DATA_OUTPUT_LOW();
        }
        LCD_WR_OUTPUT_HIGH();
    }
}

void tm1621_tx_bits_lsb(uint8_t dat, uint8_t bit_cnt)
{
    for(uint8_t i=0;i<bit_cnt;i++)
    {
        LCD_WR_OUTPUT_LOW();
        if(i < 8)
        {
            if(dat&0x01)
            {
                LCD_DATA_OUTPUT_HIGH();
            }
            else
            {
                LCD_DATA_OUTPUT_LOW();
            }
            dat>>=1;
        }
        else
        {
            LCD_DATA_OUTPUT_LOW();
        }
        LCD_WR_OUTPUT_HIGH();
    }
}


void tm1621_sw_pin_init(uint8_t wr_pin, uint8_t data_pin)
{
    wr_pin_num = wr_pin;
    data_pin_num = data_pin;
    LCD_WR_OUTPUT_INIT();
    LCD_DATA_OUTPUT_INIT();
}

